package com.zbb.online_exam.controller;

import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.zbb.online_exam.constant.Method;
import com.zbb.online_exam.dto.JsonResult;
import com.zbb.online_exam.dto.PaperDto;
import com.zbb.online_exam.dto.TableDto;
import com.zbb.online_exam.entity.Paper;
import com.zbb.online_exam.exception.ExamException;
import com.zbb.online_exam.service.ExamService;
import com.zbb.online_exam.service.PaperService;
import com.zbb.online_exam.utils.HttpUtils;
import com.zbb.online_exam.vo.AnswerVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zbbstart
 * @date 2021/2/15 - 16:59
 */
@RestController
@RequestMapping("exams")
@Slf4j
@Api(tags = "考试信息相关功能的接口")
public class ExamController {
    @Autowired
    private ExamService examService;
    @Autowired
    private PaperService paperService;
    @Autowired
    private HttpUtils httpUtils;

    /**
     * 获取当前学生当前老师所发布的试卷
     * 分页的
     */
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    @GetMapping("{userId}")
    @ApiOperation(value = "获取试卷", notes = "获取当前学生当前老师所发布的试卷")
    public JsonResult getAllPapers(@PathVariable("userId") Integer userId, HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            int pageNo = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("limit"));
            TableDto allExams = examService.getAllExams(userId, pageNo, pageSize);
            result = httpUtils.buildSuccess(Method.GET, allExams);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result = httpUtils.buildFailure(e.getMessage(), Method.GET);
        } catch (ExamException e) {
            result = httpUtils.buildFailure(e.getMessage(), Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 获取试卷信息
     */
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    @GetMapping("info/{examNo}")
    @ApiOperation(value = "获取试卷信息", notes = "根据考试编号获取试卷信息")
    public JsonResult getExamInfo(@PathVariable("examNo") String examNo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            Integer paperId = paperService.getPaperByExamNo(examNo).getPaperId();
            Paper paper = paperService.getPaperAllInfo(paperId);
            result = httpUtils.buildSuccess(Method.GET, paper);
        } catch (ExamException | ExcelImportException e) {
            result = httpUtils.buildFailure(e.getMessage(), Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 获取学生回答试卷的答案列表
     */
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    @PostMapping("{userId}")
    @ApiOperation(value = "获取学生回答试卷的答案列表", notes = "获取学生回答试卷的答案列表")
    public JsonResult getStudentAnswers(@PathVariable("userId") Integer userId, @RequestBody AnswerVo answerVo,
                                        HttpServletResponse res) {
        answerVo.setStudentNo(userId);
        JsonResult result = new JsonResult();
        try {
            examService.getStudentAnswers(answerVo);
            result = httpUtils.buildSuccess(Method.POST, "提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 查看学生的考试结果，即批改试卷
     */
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    @GetMapping(value = "{userId}", params = "examNo")
    @ApiOperation(value = "批改试卷", notes = "查看学生的考试结果")
    public JsonResult checkStudentPaper(@PathVariable("userId") Integer userId, HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            String examNo = req.getParameter("examNo");
            PaperDto paperDto = examService.checkPaper(userId, examNo);
            result.setCode(200);
            result.setData(paperDto);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

}
